﻿using System.Collections.Generic;
using System.IO;
using Neatly.Hierarchy;
using NeatlyEditor;
using Pandora;
using UnityEditor;
using UnityEngine;

namespace PandoraEditor
{
    public static class GlobalPrefabPoolTool
    {
        public static void GenerateGlobalPrefabPol(string[] addConfigArray = null)
        {
            string prefabRootPath = "assets/data/global/GlobalPrefabPool.prefab";
            PdrFileUtil.CreateDirectoryFromFile(prefabRootPath);
            string configPath = $"{NeatlyEditorConfig.PATH_PROJECT}/pandora/GlobalPrefabPool.txt";
            string[] configArray = File.ReadAllText(configPath).Split('\n');
            var go = new GameObject("GlobalPrefabPool");
            NodeHierarchy hierarchy = go.AddComponent<NodeHierarchy>();
            List<NodeHierarchy.ItemInfo> itemList = new();
            AddItemList(itemList, configArray);
            if (addConfigArray != null)
            {
                AddItemList(itemList, addConfigArray);
            }
            hierarchy.externals = itemList.ToArray();
            PrefabUtility.SaveAsPrefabAsset(hierarchy.gameObject, prefabRootPath);
            Object.DestroyImmediate(hierarchy.gameObject);
        }

        private static void AddItemList(List<NodeHierarchy.ItemInfo> itemList, string[] configArray)
        {
            var allPrefabList = PdrFindHelper.GetAllPrefabs();
            foreach (var line in configArray)
            {
                string prefabName = line.Trim();
                Debug.Log(prefabName);
                {
                    string prefabPath = GetPrefabPath(allPrefabList, prefabName);
                    if (string.IsNullOrEmpty(prefabPath))
                    {
                        Debug.LogError($"配置错误:{prefabName}");
                    }
                    else
                    {
                        AssetObject itemPrefab = AssetObject.Create<GameObject>(prefabPath);
                        itemList.Add(new NodeHierarchy.ItemInfo { name = $"Prefab{itemPrefab.gameObject.name}", item = itemPrefab.gameObject });
                    }
                }
            }
        }

        private static string GetPrefabPath(List<string> prefabList, string prefabName)
        {
            prefabName = $"/{prefabName}.prefab";
            foreach (var prefabPath in prefabList)
            {
                if (prefabPath.EndsWith(prefabName))
                {
                    return prefabPath;
                }
            }
            return null;
        }

        private static bool IsLetterOrNumber(string str)
        {
            foreach (var c in str)
            {
                if (!char.IsLetterOrDigit(c))
                {
                    return false;
                }
            }
            return true;
        }
    }
}